package core;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SimpleMarkdownToHtml implements MarkdownToHtml {

    private static final Pattern BOLD = Pattern.compile("\\*\\*(.+?)\\*\\*");
    private static final Pattern ITALIC = Pattern.compile("(?<!\\*)\\*(?!\\*)(.+?)(?<!\\*)\\*(?!\\*)");

    @Override
    public String convert(String markdown) {
        if (markdown == null || markdown.isEmpty()) return "";

        List<String> lines = splitLines(markdown);
        StringBuilder html = new StringBuilder();

        for (String raw : lines) {
            String line = raw.trim();
            if (line.isEmpty()) continue;

            if (line.startsWith("## ")) {
                String content = line.substring(3).trim();
                html.append("<h2>").append(applyInline(content)).append("</h2>\n");
            } else if (line.startsWith("# ")) {
                String content = line.substring(2).trim();
                html.append("<h1>").append(applyInline(content)).append("</h1>\n");
            } else {
                html.append("<p>").append(applyInline(line)).append("</p>\n");
            }
        }
        return html.toString();
    }

    private List<String> splitLines(String text) {
        String[] arr = text.split("\\R");
        List<String> list = new ArrayList<>(arr.length);
        for (String s : arr) list.add(s);
        return list;
    }

    private String applyInline(String text) {
        String afterBold = replaceAll(BOLD, text, "<strong>$1</strong>");
        String afterItalic = replaceAll(ITALIC, afterBold, "<em>$1</em>");
        return escapeHtmlExceptTags(afterItalic);
    }

    private String replaceAll(Pattern pattern, String input, String replacement) {
        Matcher m = pattern.matcher(input);
        StringBuffer sb = new StringBuffer();
        while (m.find()) m.appendReplacement(sb, replacement);
        m.appendTail(sb);
        return sb.toString();
    }

    private String escapeHtmlExceptTags(String input) {
        String escaped = input
                .replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
        return escaped
                .replace("&lt;strong&gt;", "<strong>")
                .replace("&lt;/strong&gt;", "</strong>")
                .replace("&lt;em&gt;", "<em>")
                .replace("&lt;/em&gt;", "</em>");
    }
}
